<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
		#topBox {
			background: #f00;
			position: fixed;
			top: -100px;
			left: 0;
			width: 100%;
			font-size: 50px;
			font-weight: bold;
			text-align: center;
			line-height: 100px;
		}

		#back {
			width: 100px;
			height: 100px;
			background-color: #abcdef;
			position: fixed;
			right: 20px;
			bottom: 50px;
			display: none;
		}
	</style>
</head>

<body>
	<div id="topBox">
		顶部通栏广告
	</div>
	<p style="width:20px;">
		锄禾日当午，汗滴禾下土。谁知盘中餐，粒粒皆辛苦。
		床前明月光，疑是地上霜。举头望明月，低头思故乡。

		离离原上草，一岁一枯荣。野火烧不尽，春风吹又生。
	</p>
	<div id="back">
		回到顶部
	</div>
</body>
<script type="text/javascript">
	var timer;
	window.onscroll = function () {
		var top = document.documentElement.scrollTop || document.body.scrollTop;
		document.querySelector("#topBox").style.top = top>=300?0:"-100px";
		// if (top >= 300) {
		// 	topBox.style.top = 0;
		// } else {
		// 	topBox.style.top = "-100px";
		// }
		document.querySelector("#back").style.display = top>=350?"block":"none";
		// if (top >= 350) {
		// 	back.style.display = "block";
		// } else {
		// 	back.style.display = "none";
		// }
	}
	document.querySelector("#back").onclick = function () {
		timer = setInterval(function () {
			console.log('定时器执行',top)
			var top = document.documentElement.scrollTop || document.body.scrollTop;
			if (top <= 0) {
				clearInterval(timer);
			}
			else {
				document.documentElement.scrollTop = top - 10;
			}
		}, 10)
	}
	// 1、当滚动距离达到300px时显示出顶部公共
	// 2、当滚动距离达到350px是显示回到顶部
	// 3、当前几回到顶部 慢慢的滑动上去
</script>

</html>